package com.zjq.smartdevice.websocket.handler;

import com.zjq.smartdevice.events.ColorCommandEvent;
import com.zjq.smartdevice.exception.MyErrorCode;
import com.zjq.smartdevice.exception.QueryDataErrorException;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * @User zhangjiaqi
 * @Project project
 * @Package com.zjq.smartdevice.websocket.handler
 * @Date 2022/3/27 22:52
 */
@Component
public class ColorCommandHandler extends BaseCommandHandler {

    @EventListener
    public void onEvent(ColorCommandEvent event) {
        System.err.println("颜色控制器发送命令");
        String deviceId = event.getDeviceId();
        String command = event.getCommand();
        //获取到会话
        WebSocketSession webSocketSession = getAllClients().get(deviceId);//获取到会话
        Assert.isTrue(webSocketSession!=null && webSocketSession.isOpen(),()->{
            throw new QueryDataErrorException("设备不在线", MyErrorCode.DEVICE_OFFLINE);
        });
        try {
            webSocketSession.sendMessage(new TextMessage(command));//给设备发送命令
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
